#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "map_file.h"

FILE *get_output(char *infilename, char **outfilename);

int main(int argc, char *argv[])
{
	if(argc < 2) {
		fprintf(stderr, "Usage: byte_to_int32 <infile> [<output.int32>]\n");
		exit(1);
	}

	ptr_range inmap = map_input_file(argv[1]);
	unsigned char *seq = (unsigned char *)inmap.sp;
	int len = (unsigned char *)inmap.ep - seq;

	// int sequence
	unsigned int *iseq = (unsigned int *)malloc(sizeof(int) * len);
	int i;
	for(i=0; i<len; i++) {
		iseq[i] = seq[i];
	}

	char *outfilename = (argc < 3) ? NULL : argv[2];
	FILE *outfile = get_output(argv[1], &outfilename);
	fwrite(iseq, sizeof(unsigned int), len, outfile);
	fclose(outfile);

	return 0;
}

FILE *get_output(char *infilename, char **outfilename)
{
	static char fnamebuf[256];
	char *fname = *outfilename;
	FILE *outfile;
	if(!fname) {
		fname = fnamebuf;
		fname = stpcpy(fname, infilename);
		stpcpy(fname, ".int32");
		fname = fnamebuf;
		*outfilename = fnamebuf;
	}
	outfile = fopen(fname, "w");
	if(!outfile) {
		perror(fname);
		exit(1);
	}
	return outfile;
}
